package com.ceac;

import java.util.Date;

import javax.ejb.EJB;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;

import javax.ejb.TimedObject;
import javax.ejb.Timer;

import javax.ejb.TimerService;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless(name="TimerSessionEJB", mappedName = "CEAC-Kronos-TimerSessionEJB")
public class TimerSessionEJBBean implements SessionBean, TimerSessionEJB,
                                            TimerSessionEJBLocal, TimedObject {
    @PersistenceContext(unitName="Kronos")
    private EntityManager em;
    private SessionContext sessionContext;
    
    public TimerSessionEJBBean() {
        System.out.println("Constructor: "+new Date());
        //TimerService ts = sessionContext.getTimerService();
        //ts.createTimer(3000, "hola");
    }
    
  public void ejbPassivate(){      
  }
  
  public void ejbActivate(){      
  }
  public void ejbRemove() {
    
  }
  public void setSessionContext(SessionContext sc) {    
      sessionContext = sc;
      System.out.println(sc);
      //System.out.println(sc.getTimerService());
  }
  public void run() {
      sessionContext.getTimerService().createTimer(200000, "hoola");
      System.out.println("run: "+new Date());
      long l = Math.round(Math.random()*2000);
      System.out.println("Sleep for "+l);
      try {
        Thread.sleep(l);
      }
      catch (InterruptedException exc) {
        System.out.println(exc);
      }
      System.out.println("Done");
  }

    public void ejbTimeout(Timer timer) {
        //System.err.println("ejbTimeout");
        System.out.println("ejbTimeout");
        run();
        //TimerService ts = sessionContext.getTimerService();
        //ts.createTimer(3000, "hola");
        
    }
}

